<template>
  <view class="phxx-item-detail">
    <view class="content-box">
      <view class="bottom block-back">
        <view class="content_wrap">
          <view class="item_wrap">
            <view class="label_wrap">
              <text>*</text>选择客户
            </view>
            <view class="value_wrap">
              <view><input class="cph1" v-model="cusName" :disabled="true" placeholder="请选择客户"
                  @click="openSelectPop('customer')" /></view>
              <uni-icons v-if="isEditType != 'update'" type="forward" size="20" color="#999999"></uni-icons>
            </view>
          </view>
          <view class="item_wrap" v-if="!!cusName && orgNameShow">
            <view class="label_wrap">
              所属组织
            </view>
            <view class="value_wrap">
              <input v-model="orgNameText" maxlength="50" disabled />
            </view>
          </view>
          <view class="item_wrap">
            <view class="label_wrap">销售方向</view>
            <view class="value_wrap">
              <view>
                <picker @change="changeCusSales" :value="cusSalesIndex" mode="selector" :range="cusSalesLists"
                  range-key="label">
                  <input v-model="cusSalesName" :disabled="true" placeholder="请选择销售方向" />
                </picker>
              </view>
              <uni-icons type="forward" size="20" color="#999999"></uni-icons>
            </view>
          </view>

          <view class="item_wrap">
            <view class="label_wrap">
              <text>*</text>卸货地址
            </view>
            <view class="value_wrap">
              <input v-model="itemList.cusAddress" placeholder="请输入卸货地址" maxlength="50" />
            </view>
          </view>

          <view class="item_wrap">
            <view class="label_wrap">
              <text>*</text>省
            </view>
            <view class="value_wrap">
              <view>
                <picker @change="changeProvince" :value="itemList.cusProvince" mode="selector" :range="provinceLists"
                  range-key="text">
                  <input v-model="itemList.provinceName" :disabled="true" placeholder="请选择省" />
                </picker>
              </view>
              <uni-icons type="forward" size="20" color="#999999"></uni-icons>
            </view>
          </view>
          <view class="item_wrap">
            <view class="label_wrap">
              <text>*</text>市
            </view>
            <view class="value_wrap">
              <view>
                <picker @change="changeCity" :value="itemList.cusCity" mode="selector" :range="cityLists"
                  range-key="text">
                  <input v-model="itemList.cityName" :disabled="true" placeholder="请选择市" />
                </picker>
              </view>
              <uni-icons type="forward" size="20" color="#999999"></uni-icons>
            </view>
          </view>
          <view class="item_wrap">
            <view class="label_wrap">
              <text>*</text>区县
            </view>
            <view class="value_wrap">
              <view>
                <picker @change="changeCuontry" :value="itemList.cusCounty" mode="selector" :range="cuontryLists"
                  range-key="text">
                  <input v-model="itemList.countyName" :disabled="true" placeholder="请选择区县" />
                </picker>
              </view>
              <uni-icons type="forward" size="20" color="#999999"></uni-icons>
            </view>
          </view>
          <view class="item_wrap">
            <view class="label_wrap">
              <text>*</text>街道
            </view>
            <view class="value_wrap">
              <view>
                <picker @change="changeTown" :value="itemList.cusTown" mode="selector" :range="townLists"
                  range-key="text">
                  <input v-model="itemList.townName" :disabled="true" placeholder="请选择街道" />
                </picker>
              </view>
              <uni-icons type="forward" size="20" color="#999999"></uni-icons>
            </view>
          </view>
        </view>
        <view class="btns">
          <button type="primary" @click="handleClick">确认</button>
        </view>
      </view>
    </view>
    <select-search ref="selectSearchRef" :title="popTitle" :show="isShow" :name="searchName" :param="paramValue"
      :value="searhValue" :type="'radio'" :dataLists="list" @search="searchFn" @cancel="isShow = false"
      @submit="submitSelectFn"></select-search>
  </view>
</template>

<script>
  import { toast } from '@/utils/common';
  import { create, update, getOne } from '@/api/unloader.js';
  import { getAreaTreesBycode } from '@/api/address.js';
  import { getDictList } from '@/api/login';
  import { getBasisDeploy } from "@/api/system/user.js"
  import { getCoalCustomer } from '@/api/sale.js';
  import { getDriverId, getTenantId } from '@/utils/auth.js';
  export default {
    data() {
      return {
        isShow: false,
        orgNameText: '',
        orgNameShow: false,
        selectType: undefined,
        searchName: 'label',
        searhValue: 'value',
        popTitle: '选择客户',
        list: [],
        paramValue: undefined,
        cusList: [],
        cusName: undefined,
        cusSalesIndex: undefined,
        cusSalesName: undefined,
        itemList: {
          id: undefined,
          cusId: undefined,
          cusAddress: undefined,
          cusSales: undefined,
          cusProvince: undefined,
          cusCity: undefined,
          cusCounty: undefined,
          cusTown: undefined,
          provinceName: undefined,
          cityName: undefined,
          countyName: undefined,
          townName: undefined,
          provinceCode: undefined,
          cityCode: undefined,
          countyCode: undefined,
          townCode: undefined,
          operatorName: this.$store.state.user.name,
          userId: getDriverId(),
          enterId: getTenantId()
        },
        provinceLists: [],
        cityLists: [],
        cuontryLists: [],
        townLists: [],
        cusSalesLists: [],
        tempDatas: {},
        isEdit: false,
        ifFirstEdit: true,
        isEditType: 'add'
      };
    },
    async onLoad(options) {
      await this.getDictLists()
      await this.getProvinces()
      if (!!options) {
        this.isEdit = true
        if (!!options.id) {
          this.isEditType = "update"
          this.getDetail(options.id)
        } else this.isEdit = false
      }
      if (!this.isEdit) {
        uni.setNavigationBarTitle({
          title: '添加'
        });
      } else {
        uni.setNavigationBarTitle({
          title: '编辑'
        });
      }
    },
    async onShow() {
      let res = await getBasisDeploy(getTenantId())
      if (res.code == 200) {
        this.orgNameShow = res?.data?.isEnabledOrganization === 1 ? true : false
      }
      this.getCoalCustomer()
    },
    methods: {
      async getDetail(id) {
        let data = await getOne(id)
        let _ = this
        if (data.code == 0) {
          _.tempDatas = data.data
          _.itemList.id = data.data.id
          _.itemList.cusId = data.data.cusId
          _.cusName = data.data.cusName
          _.orgNameText = data.data.organizationName
          _.itemList.cusAddress = data.data.cusAddress
          _.itemList.cusProvince = data.data.cusProvince
          _.itemList.provinceName = data.data.provinceName
          _.itemList.cusCity = data.data.cusCity
          _.itemList.cityName = data.data.cityName
          _.itemList.cusCounty = data.data.cusCounty
          _.itemList.countyName = data.data.countyName
          _.itemList.cusTown = data.data.cusTown
          _.itemList.townName = data.data.townName
          // 获取省的 value
          const provinceItem = this.provinceLists.find(item => item.id === data.data.cusProvince);
          if (provinceItem) {
            _.itemList.provinceCode = provinceItem.value
            await this.getCitys(provinceItem.value);
          }

          // 获取市的 value
          const cityItem = this.cityLists.find(item => item.id === data.data.cusCity);
          if (cityItem) {
            _.itemList.cityCode = cityItem.value
            await this.getCountys(cityItem.value);
          }

          // 获取区县的 value
          const countyItem = this.cuontryLists.find(item => item.id === data.data.cusCounty);
          if (countyItem) {
            _.itemList.countyCode = countyItem.value
            await this.getTowns(countyItem.value);
          }

          // 获取街道的 code
          const townItem = this.townLists.find(item => item.id === data.data.cusTown);
          if (townItem) {
            _.itemList.townCode = townItem.value
          }

          const editIndex = this.cusSalesLists.findIndex(item => Number(item.value) === data.data.cusSales);
          if (editIndex > -1) {
            this.cusSalesIndex = editIndex;
            this.itemList.cusSales = data.data.cusSales;
            this.cusSalesName = this.cusSalesLists[editIndex].label;
          }
        }
      },
      //获取客户列表
      async getCoalCustomer() {
        const res = await getCoalCustomer()
        if (res.code === 0) {
          this.cusList = res.data || []
        }
      },
      //选择客户
      openSelectPop(type) {
        if (this.isEditType === 'update') {
          return;
        }
        this.selectType = type
        this.searchName = 'cusName'
        this.searhValue = 'cusId'
        if (type === 'customer') {
          this.popTitle = '选择客户'
          this.list = JSON.parse(JSON.stringify(this.cusList))
          this.paramValue = this.itemList.cusId ? Number(this.itemList.cusId) : undefined
        }
        this.isShow = true
      },
      searchFn(keyword) {
        let list = []
        switch (this.selectType) {
          case 'customer':
            list = JSON.parse(JSON.stringify(this.cusList))
            this.list = list.filter(e => e.cusName.includes(keyword))
            break;
          default: break
        }
      },
      submitSelectFn(data) {
        this.orgNameText = data.organizationName
        switch (this.selectType) {
          case 'customer':
            this.itemList.cusId = data.cusId
            this.cusName = data.cusName
            break;
          default: break;
        }
        console.log("??????cusname==", this.cusName)
        this.isShow = false
      },
      async getDictLists() {
        const res = await getDictList();
        if (res.code === 0) {
          this.cusSalesLists = (res.data || []).filter(
            (e) => e.dictType === 'cus_sales'
          );
          // 设置默认值为 value 为 '1' 的项，并获取其索引
          const defaultOptionIndex = this.cusSalesLists.findIndex(item => item.value === '1');
          if (defaultOptionIndex > -1) {
            this.cusSalesName = this.cusSalesLists[defaultOptionIndex].label;
            this.cusSalesIndex = defaultOptionIndex;
            this.itemList.cusSales = this.cusSalesLists[defaultOptionIndex].value;
          }
        }
      },
      async getProvinces() {
        let data = await getAreaTreesBycode(0)
        if (!!data) {
          if (!!data.data && data.data.length > 0) {
            this.provinceLists = []
            data.data.forEach(item => {
              this.provinceLists.push({
                id: item.id,
                value: item.code,
                text: item.name
              })
            })
          }
        }
      },

      async getCitys(id) {
        let data = await getAreaTreesBycode(id)
        if (!!data && data.data.length > 0) {
          this.cityLists = []
          data.data.forEach(item => {
            this.cityLists.push({
              id: item.id,
              value: item.code,
              text: item.name
            })
          })
        }
      },
      async getCountys(id) {
        let data = await getAreaTreesBycode(id)
        if (!!data && data.data.length > 0) {
          this.cuontryLists = []
          data.data.forEach(item => {
            this.cuontryLists.push({
              id: item.id,
              value: item.code,
              text: item.name
            })
          })
        }
      },
      async getTowns(id) {
        let data = await getAreaTreesBycode(id)
        if (!!data && data.data.length > 0) {
          this.townLists = []
          data.data.forEach(item => {
            this.townLists.push({
              id: item.id,
              value: item.code,
              text: item.name
            })
          })
        }
      },
      changeProvince(e) {
        this.ifFirstEdit = false
        if (this.provinceLists.length > 0) {
          this.itemList.provinceName = this.provinceLists[e.detail.value].text
          this.itemList.cusProvince = this.provinceLists[e.detail.value].id
          this.itemList.provinceCode = this.provinceLists[e.detail.value].value
        }
        this.itemList.cusCity = undefined
        this.itemList.cusCounty = undefined
        this.itemList.cusTown = undefined
        this.itemList.cityName = undefined
        this.itemList.countyName = undefined
        this.itemList.townName = undefined

        this.itemList.cityCode = undefined
        this.itemList.countyCode = undefined
        this.itemList.townCode = undefined
        if (!!this.provinceLists[e.detail.value].value) this.getCitys(this.provinceLists[e.detail.value].value)
      },
      changeCity(e) {
        this.ifFirstEdit = false
        this.itemList.cusCity = e
        if (this.cityLists.length > 0) {
          this.itemList.cityName = this.cityLists[e.detail.value].text
          this.itemList.cusCity = this.cityLists[e.detail.value].id
          this.itemList.cityCode = this.cityLists[e.detail.value].value
        }
        this.itemList.cusCounty = undefined
        this.itemList.cusTown = undefined
        this.itemList.countyName = undefined
        this.itemList.townName = undefined

        this.itemList.countyCode = undefined
        this.itemList.townCode = undefined
        if (!!this.cityLists[e.detail.value].value) this.getCountys(this.cityLists[e.detail.value].value)
      },
      changeCuontry(e) {
        this.ifFirstEdit = false
        if (this.cuontryLists.length > 0) {
          this.itemList.countyName = this.cuontryLists[e.detail.value].text
          this.itemList.cusCounty = this.cuontryLists[e.detail.value].id
          this.itemList.countyCode = this.cuontryLists[e.detail.value].value
        }
        this.itemList.cusTown = undefined
        this.itemList.townName = undefined
        this.itemList.townCode = undefined
        this.isEdit = false
        if (!!this.cuontryLists[e.detail.value].value) this.getTowns(this.cuontryLists[e.detail.value].value)
      },
      changeTown(e) {
        this.ifFirstEdit = false
        if (this.townLists.length > 0) {
          this.itemList.townName = this.townLists[e.detail.value].text
          this.itemList.cusTown = this.townLists[e.detail.value].id
          this.itemList.townCode = this.cuontryLists[e.detail.value].value
        }
      },

      changeCusSales({ detail }) {
        if (this.cusSalesLists.length > 0) {
          const selectedItem = this.cusSalesLists[detail.value];
          this.cusSalesName = selectedItem.label;
          this.cusSalesIndex = detail.value;
          this.itemList.cusSales = selectedItem.value;
        }
      },
      async handleClick() {
        let data = {}
        let _ = this
        if (!_.itemList.cusId) {
          toast(`客户不能为空`);
          return
        }
        if (!_.itemList.cusAddress) {
          toast(`卸货地址不能为空`);
          return
        }
        if (!_.itemList.cusProvince) {
          toast(`省不能为空`);
          return
        }
        if (!_.itemList.cusCity) {
          toast(`市不能为空`);
          return
        }
        if (!_.itemList.cusCounty) {
          toast(`区县不能为空`);
          return
        }
        if (!_.itemList.cusTown) {
          toast(`街道不能为空`);
          return
        }
        if (_.cusSalesIndex !== undefined && this.cusSalesLists[_.cusSalesIndex]) {
          this.itemList.cusSales = Number(this.cusSalesLists[_.cusSalesIndex].value)
        }
        let msg = ""
        if (this.isEditType == 'update') {
          msg = "编辑"
          data = await update(this.itemList)
        } else {
          msg = "添加"
          data = await create(this.itemList)
        }
        if (data.code == 0) {
          uni.showToast({
            title: msg + '成功',
            icon: 'success',
            success: () => {
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1
                });
              }, 1000);
            }
          });
        } else {
          uni.showToast({
            title: msg + '失败',
            icon: 'failed'
          });
        }
      },
    }
  };
</script>

<style lang="scss" scoped>
  @import "@/static/scss/custom_form.scss";

  .cph1 {
    display: block;
    /* 确保 text 占据一行 */
    width: 100%;
    /* 或者指定一个具体宽度 */
    white-space: nowrap;
    /* 不换行 */
    overflow: hidden;
    /* 隐藏溢出内容 */
    text-overflow: ellipsis;
    /* 超出显示 ... */
  }
</style>